package com.ruoyi.activiti.service.impl;

import com.ruoyi.activiti.domain.vo.FlowVo;
import com.ruoyi.activiti.mapper.ProcessFlowsMapper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>工作流流程信息业务类</p>
 * <p>创建日期：2021-07-20</p>
 *
 * @author zhou-qf
 */
@Service
public class ProcessFlowsService {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Resource
    private ProcessFlowsMapper processFlowsMapper;


    /**
     * 获取某个流程图的所有用户任务节点
     * @param processId 实例ID
     * @return
     */
    public List<FlowVo> queryFlowList(String processId){

        List<FlowVo> flowVoList = new ArrayList<>();

        // 根据流程id获得流程模式id
        String processDefinitionId = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processId)
                .singleResult()
                .getProcessDefinitionId();
        // 获得流程模型
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);

        // 流程图关键字
        String processKey = model.getProcesses().get(0).getId();

        if(model != null) {
            // 获得流程模型的所有节点
            Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();

            int i = 0;
            for(FlowElement e : flowElements) {
                if(e instanceof UserTask){
                    List l =((UserTask) e).getCandidateUsers();
                    List g = ((UserTask) e).getCandidateGroups();

                    FlowVo flowVo = new FlowVo();
                    flowVo.setTaskName(((UserTask) e).getName());
                    if(!l.isEmpty()){
                        flowVo.setTaskUsers(l.get(0).toString());
                    }

                    if(!g.isEmpty()){
                        flowVo.setTaskGroups(g.get(0).toString());
                    }
                    flowVo.setOrderNum(++i);

                    flowVoList.add(flowVo);
                }
            }
        }
        return flowVoList;
    }

    /**
     * 获取当前实例下一节点审批用户信息
     * @param processId
     * @return
     */
    public List<String> nextNode(String processId){
        return processFlowsMapper.queryNextNode(processId);
    }

}
